<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta name="keywords" content="anhoder的进阶日志">
<meta name="description" content="一川烟草，满城风絮。">
<meta name="theme-color" content="#000">
<title>面试问题之PHP | anhoder的进阶日志</title>
<link rel="shortcut icon" href="/favicon.ico?v=1640406618472">
<link rel="stylesheet" href="/media/css/pisces.css">
<link rel="stylesheet" href="/media/fonts/font-awesome.css">
<link
  href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Rosario:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext"
  rel="stylesheet" type="text/css">

<link href="/media/hljs/styles/androidstudio.css"
  rel="stylesheet">

<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/themes/green/pace-theme-minimal.css" rel="stylesheet" />

<link rel="stylesheet" href="/styles/main.css">

<script src="/media/hljs/highlight.js"></script>
<script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.0/velocity.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.0/velocity.ui.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css"
  integrity="sha384-zB1R0rpPzHqg7Kpt0Aljp8JPLqbXI3bhnPWROx27a9N0Ll6ZP/+DiW/UqRcLbRjq" crossorigin="anonymous">


<script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.js"
  integrity="sha384-y23I5Q6l+B6vatafAwxRu/0oK/79VlbSz7Q9aiSZUvyWYIYsd+qj+o24G5ZU2zJz" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/auto-render.min.js"
  integrity="sha384-kWPLUVMOks5AQFrykwIup5lo0m3iMkkHrD0uJ4H5cjeGihAutqP0yW0J6dpFiVkI" crossorigin="anonymous"
  onload="renderMathInElement(document.body);"></script>



<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-161423102-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag() { dataLayer.push(arguments); }
  gtag('js', new Date());

  gtag('config', 'UA-161423102-1');
</script>


<script>
  var _hmt = _hmt || [];
  (function () {
    var hm = document.createElement("script");
    hm.src = "https://hm.baidu.com/hm.js?bdf14d3cd277bc2dfa9f84d19b36a686";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
  })();
</script>


  <meta name="description" content="面试问题之PHP" />
  <meta name="keywords" content="PHP" />
</head>

<body>
  <div class="head-top-line"></div>
  <div class="header-box">
    
<div class="pisces">
  <header class="header  ">
    <div class="blog-header box-shadow-wrapper bg-color " id="header">
      <div class="nav-toggle" id="nav_toggle">
        <div class="toggle-box">
          <div class="line line-top"></div>
          <div class="line line-center"></div>
          <div class="line line-bottom"></div>
        </div>
      </div>
      <div class="site-meta">       
        <div class="site-title">
          
            <a href="/" class="brand">
              <span>anhoder的进阶日志</span>
            </a>  
          
        </div>
        
          <p class="subtitle">太阳不热，糖也正适合。</p>
        
      </div>
      <nav class="site-nav" id="site_nav">
        <ul id="nav_ul">
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="/" target="_self">
                    <i class="fa fa-home"></i> 首页
                  </a>
                
              
            </li>
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="/archives/" target="_self">
                    <i class="fa fa-archive"></i> 归档
                  </a>
                
              
            </li>
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="/tags/" target="_self">
                    <i class="fa fa-tags"></i> 标签
                  </a>
                
              
            </li>
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="/post/about/" target="_self">
                    <i class="fa fa-user"></i> 关于
                  </a>
                
              
            </li>
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="https://github.com/anhoder/" target="_blank">
                    <i class="fa fa-github"></i> GitHub
                  </a>
                
              
            </li>
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="/media/excalidraw/" target="_self">
                    <i class="fa fa-picture-o"></i> 制作手绘图
                  </a>
                
              
            </li>
          
          
          
        </ul>
      </nav>
    </div>
  </header>
</div>

<script type="text/javascript"> 
 
  let showNav = true;

  let navToggle = document.querySelector('#nav_toggle'),
  siteNav = document.querySelector('#site_nav');
  
  function navClick() {
    let sideBar = document.querySelector('.sidebar');
    let navUl = document.querySelector('#nav_ul');
    navToggle.classList.toggle('nav-toggle-active');
    siteNav.classList.toggle('nav-menu-active');
    if (siteNav.classList.contains('nav-menu-active')) {
      siteNav.style = "height: " + (navUl.children.length * 42) +"px !important";
    } else {
      siteNav.style = "";
    }
  }

  navToggle.addEventListener('click',navClick);  
</script>
  </div>
  <div class="main-continer">
    
    <div
      class="section-layout pisces ">
      <div class="section-layout-wrapper">
        

<div class="sidebar">
  
    <div class="sidebar-box box-shadow-wrapper bg-color right-motion" id="sidebar">
      
        <div class="post-list-sidebar">
          <div class="sidebar-title">
            <span id="tocSideBar" class="sidebar-title-item sidebar-title-active language" data-lan="index">文章目录</span>
            <span id="metaSideBar" class="sidebar-title-item language" data-lan="preview">站点概览</span>
          </div>
        </div>
      
      <div class="sidebar-body pisces" id="sidebar_body">
        
          
            <div class="post-side-meta" id="post_side_meta">
              
<div class="sidebar-wrapper box-shadow-wrapper bg-color">
  <div class="sidebar-item">
    <img class="site-author-image right-motion" src="/images/avatar.png"/>
    <p class="site-author-name">anhoder</p>
    
  </div>
  <div class="sidebar-item side-item-stat right-motion">
    <div class="sidebar-item-box">
      <a href="/archives/">
        
        <span class="site-item-stat-count">94</span>
        <span class="site-item-stat-name language" data-lan="article">文章</span>
      </a>
    </div>
    <div class="sidebar-item-box">
      <a href="">
        <span class="site-item-stat-count">27</span>
        <span class="site-item-stat-name language" data-lan="category">分类</span>
      </a>
    </div>
    <div class="sidebar-item-box">
      <a href="/tags/">
        <span class="site-item-stat-count">27</span>
        <span class="site-item-stat-name language" data-lan="tag">标签</span>
      </a>
    </div>
  </div>
  
    
  
  
    <div class="sidebar-item sidebar-item-social">
      <div class="social-item">
        
          
            <a href="https://github.com/anhoder">
              <i class="fa fa-github-alt" title="GitHub"></i>
            </a>
          
            <a href="https://twitter.com/Alan_Albert_">
              <i class="fa fa-twitter" title="Twitter"></i>
            </a>
          
            <a href="https://weibo.com/u/5794659803">
              <i class="fa fa-weibo" title="Weibo"></i>
            </a>
          
            <a href="mailto:anhoder@88.com">
              <i class="fa fa-envelope" title="Email"></i>
            </a>
          
            <a href="https://stackoverflow.com/users/9723854/alan">
              <i class="fa fa-stack-overflow" title="StackOverflow"></i>
            </a>
          
        
        
          
            <a class="social-img" href="#">
              <img src="/media/images/custom-array-imgSocials-1617614181832-socialImg.png" />
              <i class="fa fa-weixin" title="微信公众号" ></i>
            </a>
          
        
      </div>
    </div>
  

  



</div>
            </div>
            <div class="post-toc sidebar-body-active" id="post_toc" style="opacity: 1;">
              <div class="toc-box right-motion">
  <div class="toc-wrapper  auto"
    id="toc_wrapper">
    <ul class="markdownIt-TOC">
<li>
<ul>
<li><a href="#%E5%8F%98%E9%87%8F">变量</a></li>
<li><a href="#%E5%BC%95%E7%94%A8">引用</a></li>
<li><a href="#echo-print-print_r-var_dump-printf-sprintf">echo、print、print_r、var_dump、printf、sprintf</a></li>
<li><a href="#isset-is_null-empty">isset、is_null、empty</a></li>
<li><a href="#%E8%B6%85%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F">超全局变量</a></li>
<li><a href="#%E5%B8%B8%E9%87%8F">常量</a></li>
<li><a href="#static-self-this-parent">static、self、$this、parent</a></li>
<li><a href="#require-include-require_once-include_once">require、include、require_once、include_once</a></li>
<li><a href="#%E5%B8%B8%E8%A7%81%E7%9A%84%E6%95%B0%E7%BB%84%E5%A4%84%E7%90%86%E5%87%BD%E6%95%B0">常见的数组处理函数</a></li>
<li><a href="#%E5%B8%B8%E8%A7%81%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%A4%84%E7%90%86%E5%87%BD%E6%95%B0">常见的字符串处理函数</a></li>
<li><a href="#%E5%A4%9A%E5%8F%B0%E6%9C%8D%E5%8A%A1%E5%99%A8session%E5%85%B1%E4%BA%AB%E7%9A%84%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88">多台服务器session共享的解决方案</a></li>
<li><a href="#%E9%AD%94%E6%9C%AF%E6%96%B9%E6%B3%95">魔术方法</a></li>
<li><a href="#public-protected-private-final">public、protected、private、final</a></li>
<li><a href="#server_addr-remote_addr-http_x_forwarded_for-http_client_ip">SERVER_ADDR、REMOTE_ADDR、HTTP_X_FORWARDED_FOR、HTTP_CLIENT_IP</a></li>
<li><a href="#phpini%E9%85%8D%E7%BD%AE">php.ini配置</a></li>
<li><a href="#php-fpmconf%E9%85%8D%E7%BD%AE%E4%BF%A1%E6%81%AF">php-fpm.conf配置信息</a></li>
<li><a href="#%E8%BF%9B%E7%A8%8B%E9%80%9A%E8%AE%AF%E6%96%B9%E5%BC%8F">进程通讯方式</a></li>
<li><a href="#%E5%8F%91%E8%B5%B7http%E8%AF%B7%E6%B1%82%E7%9A%84%E6%96%B9%E5%BC%8F">发起HTTP请求的方式</a></li>
<li><a href="#%E7%94%9F%E6%88%90%E5%99%A8yield%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86">生成器yield的基本原理</a></li>
<li><a href="#%E9%98%B2%E6%AD%A2%E5%86%85%E5%AD%98%E6%B3%84%E9%9C%B2%E7%9A%84%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95">防止内存泄露的解决方法</a></li>
<li><a href="#%E6%A8%A1%E6%9D%BF%E5%BC%95%E6%93%8E%E7%9A%84%E5%8E%9F%E7%90%86">模板引擎的原理</a></li>
<li><a href="#%E5%8F%8D%E5%B0%84%E7%B1%BB">反射类</a></li>
<li><a href="#%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F">正则表达式</a></li>
<li><a href="#cgi-fastcgi-php-fpm">CGI、FastCGI、PHP-FPM</a></li>
<li><a href="#php%E6%93%8D%E4%BD%9Cmysql%E6%95%B0%E6%8D%AE%E5%BA%93">PHP操作MySQL数据库</a>
<ul>
<li><a href="#mysqli%E9%9D%A2%E5%90%91%E8%BF%87%E7%A8%8B">mysqli面向过程</a></li>
<li><a href="#mysqli%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1">mysqli面向对象</a></li>
<li><a href="#pdo">PDO</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  </div>
</div>

<script>

  let lastTop = 0, lList = [], hList = [], postBody, lastIndex = -1;
  let active = 'active-show', activeClass = 'active-current';
  let tocWrapper = document.querySelector('#toc_wrapper');
  let tocContent = tocWrapper.children[0];
  let autoNumber = tocWrapper && tocWrapper.classList.contains('auto-number');

  function addTocNumber(elem, deep) {
    if (!elem) {
      return;
    }
    let prop = elem.__proto__;

    if (prop === HTMLUListElement.prototype) {
      for (let i = 0; i < elem.children.length; i++) {
        addTocNumber(elem.children[i], deep + (i + 1) + '.');
      }
    } else if (prop === HTMLLIElement.prototype) {
      // 保存li元素
      if (elem.children[0] && elem.children[0].__proto__ === HTMLAnchorElement.prototype) {
        lList.push(elem);
      }
      for (let i = 0; i < elem.children.length; i++) {
        let cur = elem.children[i];
        if (cur.__proto__ === HTMLAnchorElement.prototype) {
          if (autoNumber) {
            cur.text = deep + ' ' + cur.text;
          }
        } else if (cur.__proto__ === HTMLUListElement.prototype) {
          addTocNumber(cur, deep);
        }
      }
    }
  }

  function removeParentActiveClass() {
    let parents = tocContent.querySelectorAll('.' + active)
    parents.forEach(function (elem) {
      elem.classList.remove(active);
    });
  }

  function addActiveClass(index) {
    if (index >= 0 && index < hList.length) {
      lList[index].classList.add(activeClass);
    }
  }

  function removeActiveClass(index) {
    if (index >= 0 && index < hList.length) {
      lList[index].classList.remove(activeClass);
    }
  }

  function addActiveLiElemment(elem, parent) {
    if (!elem || elem === parent) {
      return;
    } else {
      if (elem.__proto__ === HTMLLIElement.prototype) {
        elem.classList.add(active);
      }
      addActiveLiElemment(elem.parentElement, parent);
    }
  }

  function showToc() {
    if (tocWrapper) {
      postBody = document.querySelector('#post_body');
      for (let i = 0; i < postBody.children.length; i++) {
        if (postBody.children[i].__proto__ === HTMLHeadingElement.prototype) {
          hList.push(postBody.children[i]);
        }
      }
      if (tocWrapper.classList.contains('compress')) {
        tocContent.classList.add('closed');
      } else if (tocWrapper.classList.contains('no_compress')) {
        tocContent.classList.add('expanded');
      } else {
        if (hList.length > 10) {
          active = 'active-hidden'
          tocContent.classList.add('closed');
        } else {
          tocContent.classList.add('expanded');
        }
      }
    }
  }

  (function () {
    // 处理不是从#一级标题开始目录
    if (tocContent.children.length === 1 && tocContent.children[0].__proto__ === HTMLLIElement.prototype) {
      let con = tocContent.children[0].children[0];
      tocContent.innerHTML = con.innerHTML;
    }
    let markdownItTOC = document.querySelector('.markdownIt-TOC');
    let innerHeight = window.innerHeight;
    markdownItTOC.style = `max-height: ${innerHeight - 80 > 0 ? innerHeight - 80 : innerHeight}px`
    addTocNumber(tocContent, '');
  })();

  document.addEventListener('scroll', function (e) {
    if (lList.length <= 0) {
      return;
    }
    let scrollTop = document.scrollingElement.scrollTop + 10;
    let dir;

    if (lastTop - scrollTop > 0) {
      dir = 'up';
    } else {
      dir = 'down';
    }

    lastTop = scrollTop;
    if (scrollTop <= 0) {
      if (lastIndex >= 0 && lastIndex < hList.length) {
        lList[lastIndex].classList.remove(activeClass);
      }
      return;
    }

    let current = 0, hasFind = false;
    for (let i = 0; i < hList.length; i++) {
      if (hList[i].offsetTop > scrollTop) {
        current = i;
        hasFind = true;
        break;
      }
    }
    if (!hasFind && scrollTop > lList[lList.length - 1].offsetTop) {
      current = hList.length - 1;
    } else {
      current--;
    }
    if (dir === 'down') {
      if (current > lastIndex) {
        addActiveClass(current);
        removeActiveClass(lastIndex)
        lastIndex = current;
        removeParentActiveClass();
        lList[current] && addActiveLiElemment(lList[current].parentElement, tocContent);
      }
    } else {
      if (current < lastIndex) {
        addActiveClass(current);
        removeActiveClass(lastIndex);
        lastIndex = current;
        removeParentActiveClass();
        lList[current] && addActiveLiElemment(lList[current].parentElement, tocContent);
      }
    }
  });


  window.addEventListener('load', function () {
    showToc();
    document.querySelector('#sidebar').style = 'display: block;';
    tocWrapper.classList.add('toc-active');
    setTimeout(function () {
      if ("createEvent" in document) {
        let evt = document.createEvent("HTMLEvents");
        evt.initEvent("scroll", false, true);
        document.dispatchEvent(evt);
      }
      else {
        document.fireEvent("scroll");
      }
    }, 500)
  })

</script>
            </div>
          
        
      </div>
    </div>
  
</div>
<script>
  const SIDEBAR_TITLE_ACTIVE = 'sidebar-title-active';
  const SIDEBAR_BODY_ACTIVE = 'sidebar-body-active';
  const SLIDE_UP_IN = 'slide-up-in';

  let sidebar = document.querySelector('#sidebar'),
  tocSideBar = document.querySelector('#tocSideBar'),
  metaSideBar = document.querySelector('#metaSideBar'),
  postToc = document.querySelector('#post_toc'),
  postSiteMeta = document.querySelector('#post_side_meta'),
  sidebarTitle = document.querySelector('.sidebar-title'),
  sidebarBody = document.querySelector('#sidebar_body');

  tocSideBar && tocSideBar.addEventListener('click', (e) => {
    toggleSidebar(e);
  });

  metaSideBar && metaSideBar.addEventListener('click', (e) => {
    toggleSidebar(e);
  });

  function toggleSidebar(e) {
    let currentTitle = document.querySelector("."+SIDEBAR_TITLE_ACTIVE);
    if (currentTitle == e.srcElement) {
      return ;
    }
    let current, showElement, hideElement;
    if (e.srcElement == metaSideBar) {
      showElement = postSiteMeta;
      hideElement = postToc;
    } else if (e.srcElement == tocSideBar){
      showElement = postToc;
      hideElement = postSiteMeta;
    }
    currentTitle.classList.remove(SIDEBAR_TITLE_ACTIVE);
    e.srcElement.classList.add(SIDEBAR_TITLE_ACTIVE);

    window.Velocity(hideElement, 'stop');
    window.Velocity(hideElement, 'transition.slideUpOut', {
      display: 'none',
      duration: 200,
      complete: function () {
        window.Velocity(showElement, 'transition.slideDownIn', {
          duration: 200
        });
      }
    })
    hideElement.classList.remove(SIDEBAR_BODY_ACTIVE);
    showElement.classList.add(SIDEBAR_BODY_ACTIVE);
  }

  postToc && postToc.addEventListener('transitionend', function() {
    this.classList.remove(SLIDE_UP_IN);
  });

  if (sidebarBody) {
    if (sidebarBody.classList.contains('pisces') || sidebarBody.classList.contains('gemini')) {
      let hasFix = false;
      let scrollEl = document.querySelector('.main-continer');
      let limitTop = document.querySelector('#nav_ul').children.length * 42 + 162;
      window.addEventListener('scroll', function(e) {
        if (document.scrollingElement.scrollTop >= limitTop) {
          if (!hasFix) {
            sidebar.classList.add('sidebar-fixed');
            hasFix = true;
          }
        } else {
          if (hasFix) {
            sidebar.classList.remove('sidebar-fixed');
            hasFix = false;
          }
        }
      });
    }
  }
  
</script>
        <div class="section-box box-shadow-wrapper">
          <div class="section bg-color post post-page">
            <section class="post-header">
  <h1 class="post-title">
    <a class="post-title-link" href="/post/nDsg9NX3r/">
      面试问题之PHP
    </a>
  </h1>
  <div class="post-meta">
    
    <span class="meta-item pc-show">
      <i class="fa fa-calendar-o"></i>
      <span class="language" data-lan="publish">发布于</span>
      <span class="publish-time" data-t="2019-07-01 19:40:55">2019-07-01</span>
      <span class="post-meta-divider pc-show">|</span>
    </span>
    
    <span class="meta-item">
      <i class="fa fa-folder-o"></i>
      <span class="pc-show language" data-lan="category-in">分类于</span>
      
      
      <a href="/tag/wKIDH6M-M/">
        <span>PHP</span>
      </a>
      
      
    </span>
    <span class="post-meta-divider">|</span>
    
    <span class="meta-item">
      <i class="fa fa-clock-o"></i>
      <span>12<span class="language" data-lan="minute">分钟</span></span>
    </span>
    <span class="meta-item">
      <span class="post-meta-divider">|</span>
      <i class="fa fa-file-word-o"></i>
      <span>3057<span class="pc-show language" data-lan="words">字数</span></span>
    </span>
    
  </div>
</section>
            <div class="post-body next-md-body" id="post_body">
              <blockquote>
<p>博客内容为<a href="https://github.com/colinlet/PHP-Interview-QA">PHP-Interview-QA</a>读后笔记</p>
</blockquote>
<!-- more -->
<h2 id="变量">变量</h2>
<ul>
<li>PHP中的八大数据类型：整型、字符串、浮点型、布尔、数组、对象、NULL、资源。</li>
<li>字符串的定义：单引号、双引号、NowDoc及HereDoc。双引号包裹的字符串会被解析，单引号的不会。</li>
<li>判断语句中被判定为false的情况：0、0.0、'0'、''、array()、null、false</li>
</ul>
<h2 id="引用">引用</h2>
<ul>
<li>引用计数、写时复制（对象除外）</li>
<li>unset不销毁内存空间、只是取消引用</li>
</ul>
<h2 id="echo-print-print_r-var_dump-printf-sprintf">echo、print、print_r、var_dump、printf、sprintf</h2>
<blockquote>
<p>echo、print属于语言结构，print_r、var_dump、printf、sprintf是普通函数</p>
</blockquote>
<ul>
<li>echo：输出一个或多个字符串（echo '123', '345', '567';）</li>
<li>print：输出字符串</li>
<li>print_r：可输出复杂数据类型Array、Object，布尔类型true输出为1，false输出为0</li>
<li>var_dump：可输出复杂数据类型Array、Object，布尔输出正常</li>
<li>printf：格式化输出</li>
<li>sprintf：格式化返回</li>
</ul>
<h2 id="isset-is_null-empty">isset、is_null、empty</h2>
<ul>
<li>isset：当变量为NULL、声明后未赋值或者变量未声明时，返回false</li>
<li>is_null：当变量为NULL、声明后未赋值或者变量未声明时，返回true（当变量未声明或未赋值时，PHP输出警告）</li>
<li>empty：当变量为空字符串、false、array()、null、&quot;0&quot;、0、0.0或变量未声明时，返回true</li>
</ul>
<h2 id="超全局变量">超全局变量</h2>
<ul>
<li>$GLOBALS: 包含以下8个</li>
<li>$_GET: 请求的GET参数</li>
<li>$_POST: 请求的POST参数</li>
<li>$_FILES: 提交的文件信息</li>
<li>$_REQUEST: 请求参数，包含GET及POST的参数</li>
<li>$_COOKIE: 请求中携带的cookie数据</li>
<li>$_SESSION: 服务器中的session数据</li>
<li>$_ENV: 服务器系统的环境变量</li>
<li>$_SERVER: 服务器脚本信息、客户端信息、请求信息</li>
</ul>
<h2 id="常量">常量</h2>
<ul>
<li>const：语言结构，可以在类中定义常量，数据更快</li>
<li>define：函数</li>
</ul>
<blockquote>
<p>PHP中预定义的常量（魔术常量）：<strong>DIR</strong>、<strong>FILE</strong>、<strong>LINE</strong>、<strong>NAMESPACE</strong>、<strong>CLASS</strong>、<strong>TRAIT</strong>、<strong>FUNCTION</strong>、<strong>METHOD</strong></p>
</blockquote>
<h2 id="static-self-this-parent">static、self、$this、parent</h2>
<ul>
<li>static表示当前实例化的类，不能用于访问非静态属性</li>
<li>self表示当前语句所在的类，也不能用于访问非静态属性，</li>
<li>$this指的是实际实例化的对象，其不能访问静态属性和常量，且不能出现于静态方法中</li>
<li>parent指向父类，用于访问父类public的方法及静态常量</li>
</ul>
<h2 id="require-include-require_once-include_once">require、include、require_once、include_once</h2>
<p>require引用文件出错时报致命错误，并终止脚本执行，include引用文件出错时报警告，但继续执行后续脚本。</p>
<p>require_once、include_once与require、include类似，但文件只会被包含一次。因为包含前存在判断，所以性能比require、include较差。</p>
<blockquote>
<p>应尽量不使用include_once、require_once</p>
</blockquote>
<h2 id="常见的数组处理函数">常见的数组处理函数</h2>
<ul>
<li>array_count_values: 统计数组中各个value的个数</li>
<li>array_diff: 判断一个数组与其他数组的差异，返回在第一个数组中但不在其他数组中的元素，例如array_duff([1,2,3,4], [1,2], [4])返回[2 =&gt; 3]</li>
<li>array_key_exists: 判断key是否存在</li>
<li>in_array: 判断值是否存在于数组中</li>
<li>array_keys: 获取数组的所有键</li>
<li>array_values: 获取数组的所有值</li>
<li>array_merge: 合并数组，后者覆盖前者。使用“+”则是前者覆盖后者</li>
<li>sort: 数组排序</li>
<li>count: 数组长度，等同于sizeof</li>
<li>array_shift: 删除数组第一个元素，并返回</li>
<li>array_unshift: 在数组头部加入一个元素</li>
<li>array_pop: 删除数组末尾最后一个元素，并返回</li>
<li>array_push: 向数组末尾添加一个元素</li>
<li>array_reverse: 翻转数组</li>
<li>array_rand: 从数组中取随机值</li>
<li>array_flip: 交换数组的键值</li>
<li>array_search: 搜索数组的值，返回第一个匹配到的元素的键</li>
<li>array_sum: 计算数组所有值的和</li>
<li>array_slice: 根据开始位置和长度复制数组元素，返回复制的元素（即原数组不改变）</li>
<li>array_splice: 根据开始位置和长度剪切数组元素，并返回剪切的元素（即原数组中匹配到的元素被删除）</li>
<li>array_map: 对数组进行遍历，并对每个元素使用提供的回调函数</li>
</ul>
<h2 id="常见的字符串处理函数">常见的字符串处理函数</h2>
<ul>
<li>chr: ASCII码转字符</li>
<li>ord: 字符转ASCII码</li>
<li>count_chars: 统计字符串中的字符数</li>
<li>str_word_count: 统计字符串中的单词数</li>
<li>explode: 按指定字符将字符串分解为数组</li>
<li>implode: 按指定字符将数组合并为字符串</li>
<li>htmlentities: 转义处理字符串中的HTML实体。html_entity_decode用于反向解码</li>
<li>htmlspecialchars: 转义处理字符串中的特殊字符，包括&amp;、&quot;、'、&lt;、&gt;。htmlspecialchars_decode用于反向解码</li>
<li>trim: 去除字符串两端的空格，ltrim、rtrim分别用于去除左边界的空格和右边界的空格</li>
<li>str_len: 计算字符串长度</li>
<li>strrev: 翻转字符串</li>
<li>substr: 根据起始位置和长度获取子字符串，返回获取的子字符串</li>
<li>preg_replace: 正则表达式替换</li>
<li>preg_match: 正则表达式匹配</li>
<li>strstr: 判断字符串2是否为字符串1的子字符串，如果是，返回匹配到的开始位置到父字符串末尾的字符串，如果不是，返回null</li>
<li>strrchr: 与strstr一样，只是该函数从父字符串的末尾开始匹配</li>
<li>strcmp: 字符串比较函数，如果字符串1&gt;字符串2，返回1；如果字符串1&lt;字符串2，返回-1；如果字符串1等于字符串2，返回0；如果两个字符串部分内容不一致，返回两个字符串中第一个不同的字符的差值</li>
<li>str_replace: 搜索并替换字符串的内容</li>
</ul>
<h2 id="多台服务器session共享的解决方案">多台服务器session共享的解决方案</h2>
<ul>
<li>将session数据存储到MySQL数据库中</li>
<li>将session数据存储到Redis、MemCache这些内存型数据库中</li>
<li>使用NFS共享session文件</li>
<li>使用cookie保存session信息</li>
</ul>
<h2 id="魔术方法">魔术方法</h2>
<ul>
<li>__construct()</li>
<li>__destruct()</li>
<li>__call(): 当调用不存在的方法时</li>
<li>__callStatic(): 当调用不存在的惊天方法时</li>
<li>__get(): 获取不存在的属性时</li>
<li>__set(): 写入不存在的属性时</li>
<li>__sleep(): 当对象被序列化时</li>
<li>__wakeup(): 反序列化时</li>
<li>__toString(): 对象作为字符串使用时</li>
<li>__invoke(): 当对象被作为函数调用时</li>
<li>__isset(): 当使用isset函数探测对象的私有属性时</li>
<li>__unset(): 当使用unset函数删除对象的私有属性时</li>
<li>__clone(): 当对象被克隆</li>
</ul>
<h2 id="public-protected-private-final">public、protected、private、final</h2>
<ul>
<li>public可被外部访问，protected与private不可被外部访问</li>
<li>public、protected可被子类继承，private不可被继承</li>
<li>final描述的方法，不可被子类重写；final描述的类，不可被继承</li>
</ul>
<h2 id="server_addr-remote_addr-http_x_forwarded_for-http_client_ip">SERVER_ADDR、REMOTE_ADDR、HTTP_X_FORWARDED_FOR、HTTP_CLIENT_IP</h2>
<ul>
<li>SERVER_ADDR获取服务器IP</li>
<li>REMOTE_ADDR获取客户端IP，但当用户使用代理时，获取到的就是代理服务器的IP</li>
<li>HTTP_X_FORWARDED_FOR、HTTP_CLIENT_IP可以获取到用户真实IP及使用的各个代理的IP，但该字段可能被伪造</li>
</ul>
<blockquote>
<p>当后端架构中有使用到代理服务器，可以使用HTTP_X_FORWARDED_FOR、HTTP_CLIENT_IP来进行获取用户IP。如果后端服务器直接暴露给用户，只需要使用REMOTE_ADDR获取客户端IP即可。</p>
</blockquote>
<h2 id="phpini配置">php.ini配置</h2>
<table>
<thead>
<tr>
<th>配置项</th>
<th>默认值</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>short_open_tag</td>
<td>On</td>
<td>是否开启缩写模式</td>
</tr>
<tr>
<td>precision</td>
<td>14</td>
<td>浮点数显示有效数字的位数</td>
</tr>
<tr>
<td>disable_functions</td>
<td></td>
<td>禁用的函数</td>
</tr>
<tr>
<td>disable_classes</td>
<td></td>
<td>禁用的类</td>
</tr>
<tr>
<td>expose_php</td>
<td>On</td>
<td>是否暴露PHP被安装在服务器上</td>
</tr>
<tr>
<td>max_execution_time</td>
<td>30</td>
<td>最大执行时间</td>
</tr>
<tr>
<td>memory_limit</td>
<td>128M</td>
<td>每个脚本执行时内存限制</td>
</tr>
<tr>
<td>error_reporting</td>
<td>E_ALL &amp; ~E_DEPRECATED &amp; ~E_STRICT</td>
<td>设置错误报告级别</td>
</tr>
<tr>
<td>display_errors</td>
<td>On</td>
<td>显示错误</td>
</tr>
<tr>
<td>log_errors</td>
<td>On</td>
<td>设置是否将错误日志记录到error_log</td>
</tr>
<tr>
<td>error_log</td>
<td></td>
<td>PHP错误日志文件</td>
</tr>
<tr>
<td>upload_max_filesize</td>
<td>2M</td>
<td>上传文件的最大限制</td>
</tr>
<tr>
<td>post_max_size</td>
<td>8M</td>
<td>设置POST最大数据限制</td>
</tr>
</tbody>
</table>
<h2 id="php-fpmconf配置信息">php-fpm.conf配置信息</h2>
<table>
<thead>
<tr>
<th>配置项</th>
<th>默认</th>
<th>备注</th>
</tr>
</thead>
<tbody>
<tr>
<td>pid</td>
<td></td>
<td>pid文件</td>
</tr>
<tr>
<td>error_log</td>
<td></td>
<td>错误日志的位置</td>
</tr>
<tr>
<td>log_level</td>
<td>notice</td>
<td>错误级别（alert: 必须立即处理；error: 错误信息；warning: 警告信息；notice: 一般重要信息；debug: 调试信息）</td>
</tr>
<tr>
<td>daemonize</td>
<td>yes</td>
<td>设置FPM后台运行</td>
</tr>
<tr>
<td>listen</td>
<td></td>
<td>FPM监听的地址及端口</td>
</tr>
<tr>
<td>request_slowlog_timeout</td>
<td>0</td>
<td>慢日志记录阈值</td>
</tr>
<tr>
<td>slowlog</td>
<td></td>
<td>慢日志记录文件</td>
</tr>
</tbody>
</table>
<h2 id="进程通讯方式">进程通讯方式</h2>
<ul>
<li>消息队列</li>
<li>socket</li>
<li>信号量</li>
<li>共享内存</li>
<li>管道</li>
</ul>
<h2 id="发起http请求的方式">发起HTTP请求的方式</h2>
<ul>
<li>curl: curl_init -&gt; curl_setopt -&gt; curl_exec -&gt; curl_close</li>
<li>file_get_contents: http_build_query -&gt; stream_context_create -&gt; file_get_content(url, false, context)</li>
<li>fopen: fopen -&gt; fgets -&gt; fclose</li>
<li>fsockopen: fsocketopen -&gt; fputs -&gt; fgets -&gt; fclose</li>
</ul>
<h2 id="生成器yield的基本原理">生成器yield的基本原理</h2>
<blockquote>
<p>当一个生成器被调用的时候，它返回一个可以被遍历的对象。<br>
当你遍历这个对象的时候 (例如通过一个 foreach 循环)，PHP 将会在每次需要值的时候调用生成器函数，并在产生一个值之后保存生成器的状态，这样它就可以在需要产生下一个值的时候恢复调用状态。</p>
<p>一旦不再需要产生更多的值，生成器函数可以简单退出，而调用生成器的代码还可以继续执行，就像一个数组已经被遍历完了。</p>
</blockquote>
<p>此外，yield还可以接受值：</p>
<pre><code class="language-php">function printer()
{
    while (true) {
        printf(&quot;receive: %s\n&quot;, yield);
    }
}

$printer = printer();

$printer-&gt;send('hello');
$printer-&gt;send('world');
</code></pre>
<p>PHP的生成器还实现了一个send方法，该方法向yield处传递一个值，同时从 yied 语句处继续执行，直至再次遇到 yield 后控制权回到外部。</p>
<p>Generator生成器提供的方法有：</p>
<ul>
<li>current: 获取生成器当前的值</li>
<li>getReturn: 获取生成器返回的值</li>
<li>key: 获取生成器当前的key</li>
<li>next: 继续执行生成器</li>
<li>rewind: 重置生成器</li>
<li>send: 发送值给生成器</li>
<li>valid: 验证生成器是否关闭</li>
<li>throw: 抛出一个生成器异常</li>
</ul>
<h2 id="防止内存泄露的解决方法">防止内存泄露的解决方法</h2>
<ul>
<li>过大的数据分段读取</li>
<li>尽可能减少静态变量的使用，可以考虑使用引用代替</li>
<li>数据库、文件操作完后，及时释放连接</li>
<li>对象、变量使用完后，及时unset释放</li>
<li>unset()函数只能在变量值占用内存空间超过256字节时才会释放内存空间</li>
<li>当指向该变量的所有变量（如引用变量）都被销毁后，才会释放内存</li>
</ul>
<h2 id="模板引擎的原理">模板引擎的原理</h2>
<ul>
<li>通过视图名找到相应的视图文件</li>
<li>通过正则表达式或其它方式将模板引擎的定界符及其他符号修改为PHP的定界符和符号</li>
<li>将转化好的文件内容存为缓存文件，并以视图文件的上一次修改时间作为缓存文件的命名依据，保证视图文件更新后，缓存文件也进行更新</li>
</ul>
<h2 id="反射类">反射类</h2>
<ul>
<li>ReflectionClass</li>
<li>ReflectionFunction</li>
<li>ReflectionMethod</li>
<li>ReflectionObject</li>
<li>ReflectionGenerator</li>
<li>...</li>
</ul>
<h2 id="正则表达式">正则表达式</h2>
<ul>
<li>\d: 数字</li>
<li>\D: 非数字</li>
<li>\w: 字母、数字、下划线</li>
<li>\W: 非字母、数字、下划线</li>
<li>\s: 空白符，空格、制表、换行</li>
<li>\S: 非空白符</li>
<li>.: 除换行外的任意字符</li>
<li>*: 0~n个</li>
<li>?: 0或1个</li>
<li>+: 1~n个</li>
<li>{n}: n个</li>
<li>{n,}: 大于等于n个</li>
<li>{n,m}: n~m个</li>
<li>^: 开始</li>
<li>$: 结束</li>
<li>[]: 匹配中括号中任意一个</li>
<li></li>
<li>(): 整体或后文引用</li>
</ul>
<blockquote>
<p>修正符:<br>
i: 区分大小写<br>
S: .包括换行<br>
m: 每一行分别进行匹配<br>
U: 取消贪婪模式，另一种方法就是在量词后面加问号，如*?<br>
u: utf8中文匹配</p>
</blockquote>
<h2 id="cgi-fastcgi-php-fpm">CGI、FastCGI、PHP-FPM</h2>
<ul>
<li>
<p>CGI: 通用网关接口，是Web服务器与服务端语言交互的标准接口。在一个请求到来时，服务器创建一个CGI进程用来执行程序，等待程序执行完成，该CGI进程被杀死。</p>
</li>
<li>
<p>FastCGI: 是用于提升CGI性能的标准，FastCGI要求CGI进程在处理完请求后不被立刻杀死，而是保留下来，等待处理下一次请求。</p>
</li>
<li>
<p>PHP-FPM: FastCGI Processor Manager，实现FastCGI的管理器，使用FastCGI标准管理CGI程序</p>
</li>
</ul>
<h2 id="php操作mysql数据库">PHP操作MySQL数据库</h2>
<h3 id="mysqli面向过程">mysqli面向过程</h3>
<pre><code class="language-php">// 使用prepare（推荐）
$conn = mysqli_connect('127.0.0.1', 'root', '', 'test');
mysqli_set_charset($conn, 'utf8');
$stmt = mysqli_prepare($conn, 'SELECT `name`, `phone` FROM `aihailin` LIMIT ?');
mysqli_stmt_bind_param($stmt, 'i', $limit);
$limit = 2;
mysqli_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
foreach ($result as $row) {
  var_dump($row);
}
// 或不使用prepare
$conn = mysqli_connect('127.0.0.1', 'root', '', 'test');
mysqli_set_charset($conn, 'utf8');
$res = mysqli_query($conn, 'SELECT * FROM `aihailin` LIMIT 2');
foreach ($res as $row) {
  var_dump($row);
}
</code></pre>
<h3 id="mysqli面向对象">mysqli面向对象</h3>
<pre><code class="language-php">$mysqli = new mysqli('127.0.0.1', 'root', '', 'test');
$mysqli-&gt;set_charset('utf8');
$stmt = $mysqli-&gt;prepare('SELECT `name`, `phone` FROM `aihailin` LIMIT ?');
$stmt-&gt;bind_param('i', $limit);
$limit = 2;
$stmt-&gt;execute();
$result = $stmt-&gt;get_result();
foreach ($result as $row) {
  var_dump($row);
}
</code></pre>
<h3 id="pdo">PDO</h3>
<pre><code class="language-php">$dsn = 'mysql:host=127.0.0.1;dbname=test;charset=utf8';
$pdo = new PDO($dsn, 'root', '');
$stmt = $pdo-&gt;prepare('SELECT * FROM `aihailin` LIMIT :limit');
$stmt-&gt;bindParam(':limit', $limit);
$limit = 5;
if ($stmt-&gt;execute()) {
    $result = $stmt-&gt;fetchAll(PDO::FETCH_ASSOC);
    var_dump($result);
}
</code></pre>

            </div>
            
            
              <div class="post-footer">
  <ul class="post-copyright">
    <li class="post-copyright-author">
      <strong class="language" data-lan="author">本文作者：</strong>
      anhoder
    </li>
    <li class="post-copyright-link">
      <strong class="language" data-lan="link">本文链接：</strong>
      <a href="/post/nDsg9NX3r/" title="面试问题之PHP">/post/nDsg9NX3r/</a>
    </li>
    <li class="post-copyright-license">
      <strong class="language" data-lan="copyright">版权声明： </strong>
      本博客所有文章除特别声明外，均采用<a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i> BY-NC-SA</a> 许可协议。转载请注明出处！
    </li>
  </ul>
  <div class="tags">
    
      <a href="/tag/wKIDH6M-M/"># PHP</a>
    
  </div>
  <div class="nav">
    <div class="nav-prev">
      
        <i class="fa fa-chevron-left"></i>
        <a class="nav-pc-next" title="面试问题之数据结构及算法" href="/post/QqXXeBu-i/">面试问题之数据结构及算法</a class="nav-pc-next">
        <a class="nav-mobile-prev" title="面试问题之数据结构及算法" href="/post/QqXXeBu-i/">上一篇</a>
      
    </div>
    <div class="nav-next">
      
        <a class="nav-pc-next" title="面试问题之Web" href="/post/Vyg8SHrxV/">面试问题之Web</a>
        <a class="nav-mobile-next" title="面试问题之Web" href="/post/Vyg8SHrxV/">下一篇</a>
        <i class="fa fa-chevron-right"></i>
      
    </div>
  </div>
</div>
            
            
  
    
      <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
<script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

<div id="gitalk-container"></div>

<script>
  var gitalk = new Gitalk({
    clientID: '8254f894b17fffeef6e2',
    clientSecret: 'aa345603999774a44649ad73ef7fe72ee45a021b',
    repo: 'personal-blog-comments',
    owner: 'anhoder',
    admin: ['anhoder'],
    id: (location.pathname).substring(0, 49),      // Ensure uniqueness and length less than 50
    distractionFreeMode: false  // Facebook-like distraction free mode
  })
  gitalk.render('gitalk-container')
</script>
    
    
  

          </div>
        </div>
      </div>
    </div>
    <div class="footer-box">
  <footer class="footer">
    <div class="poweredby">
      © Authored by <a href="https://github.com/anhoder">anhoder</a> since 2019.
    </div>
    <div class="copyright">
      Powered by <a href="https://github.com/getgridea/gridea" target="_blank">Gridea</a> | Theme By <a
        href="https://github.com/hsxyhao/gridea-theme-next" target="_blank">HsxyHao</a>
    </div>
  </footer>
  
  
  <div class="pisces back-to-top" id="back_to_top">
    <i class="fa fa-arrow-up"></i>
    
    <span class="scrollpercent">
      <span id="back_to_top_text">0</span>%
    </span>
    
  </div>
  
  
  
<link rel="stylesheet" href="/media/live2d/css/live2d.css" />
<div class="box-scale">
  <div id="landlord" style="left: 100%px;bottom: 100%px;"
    data-key="">
    <canvas id="live2d" width="500" height="560" class="live2d"></canvas>
    
  </div>
</div>
<div id="open_live2d">召唤看板娘</div>
<script src="https://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
  var message_Path = 'https://cdn.jsdelivr.net/gh/anhoder/source-for-blog@master/';
  let landlord = document.querySelector('#landlord');
  var apiKey = landlord.dataset.key;
</script>
<script type="text/javascript" src="/media/live2d/js/live2d.js"></script>
<script>
	var home_Path = document.location.protocol + '//' + window.document.location.hostname + ":" + window.document.location.port + '/';
	var userAgent = window.navigator.userAgent.toLowerCase();
	var norunAI = ["android", "iphone", "ipod", "ipad", "windows phone", "mqqbrowser", "msie", "trident/7.0"];
	var norunFlag = false;

	for (var i = 0; i < norunAI.length; i++) {
		if (userAgent.indexOf(norunAI[i]) > -1) {
			norunFlag = true;
			break;
		}
	}

	if (!window.WebGLRenderingContext) {
		norunFlag = true;
	}

	if (!norunFlag) {
		var hitFlag = false;
		var AIFadeFlag = false;
		var liveTlakTimer = null;
		var sleepTimer_ = null;
		var AITalkFlag = false;
		var talkNum = 0;
		(function () {
			function renderTip(template, context) {
				var tokenReg = /(\\)?\{([^\{\}\\]+)(\\)?\}/g;
				return template.replace(tokenReg, function (word, slash1, token, slash2) {
					if (slash1 || slash2) {
						return word.replace('\\', '');
					}
					var variables = token.replace(/\s/g, '').split('.');
					var currentObject = context;
					var i, length, variable;
					for (i = 0, length = variables.length; i < length; ++i) {
						variable = variables[i];
						currentObject = currentObject[variable];
						if (currentObject === undefined || currentObject === null) return '';
					}
					return currentObject;
				});
			}

			String.prototype.renderTip = function (context) {
				return renderTip(this, context);
			};

			var re = /x/;
			re.toString = function () {
				showMessage('哈哈，你打开了控制台，是想要看看我的秘密吗？', 5000);
				return '';
			};

			$(document).on('copy', function () {
				showMessage('你都复制了些什么呀，转载要记得加上出处哦~~', 5000);
			});

			function initTips() {
				$.ajax({
					cache: true,
					url: message_Path + 'message.json',
					dataType: "json",
					success: function (result) {
						$.each(result.mouseover, function (index, tips) {
							$(tips.selector).mouseover(function () {
								var text = tips.text;
								if (Array.isArray(tips.text)) text = tips.text[Math.floor(Math.random() * tips.text.length + 1) - 1];
								text = text.renderTip({ text: $(this).text() });
								showMessage(text, 3000);
								talkValTimer();
								clearInterval(liveTlakTimer);
								liveTlakTimer = null;
							});
							$(tips.selector).mouseout(function () {
								showHitokoto();
								if (liveTlakTimer == null) {
									liveTlakTimer = window.setInterval(function () {
										showHitokoto();
									}, 15000);
								};
							});
						});
						$.each(result.click, function (index, tips) {
							$(tips.selector).click(function () {
								if (hitFlag) {
									return false
								}
								hitFlag = true;
								setTimeout(function () {
									hitFlag = false;
								}, 8000);
								var text = tips.text;
								if (Array.isArray(tips.text)) text = tips.text[Math.floor(Math.random() * tips.text.length + 1) - 1];
								text = text.renderTip({ text: $(this).text() });
								showMessage(text, 3000);
							});
							clearInterval(liveTlakTimer);
							liveTlakTimer = null;
							if (liveTlakTimer == null) {
								liveTlakTimer = window.setInterval(function () {
									showHitokoto();
								}, 15000);
							};
						});
					}
				});
			}
			initTips();

			var text;
			if (document.referrer !== '') {
				var referrer = document.createElement('a');
				referrer.href = document.referrer;
				text = '嗨！来自 <span style="color:#0099cc;">' + referrer.hostname + '</span> 的朋友！';
				var domain = referrer.hostname.split('.')[1];
				if (domain == 'baidu') {
					text = '嗨！ 来自 百度搜索 的朋友！<br>欢迎访问<span style="color:#0099cc;">「 ' + document.title.split(' - ')[0] + ' 」</span>';
				} else if (domain == 'so') {
					text = '嗨！ 来自 360搜索 的朋友！<br>欢迎访问<span style="color:#0099cc;">「 ' + document.title.split(' - ')[0] + ' 」</span>';
				} else if (domain == 'google') {
					text = '嗨！ 来自 谷歌搜索 的朋友！<br>欢迎访问<span style="color:#0099cc;">「 ' + document.title.split(' - ')[0] + ' 」</span>';
				}
			} else {
				if (window.location.href == home_Path) { //主页URL判断，需要斜杠结尾
					var now = (new Date()).getHours();
					if (now > 23 || now <= 5) {
						text = '你是夜猫子呀？这么晚还不睡觉，明天起的来嘛？';
					} else if (now > 5 && now <= 7) {
						text = '早上好！一日之计在于晨，美好的一天就要开始了！';
					} else if (now > 7 && now <= 11) {
						text = '上午好！工作顺利嘛，不要久坐，多起来走动走动哦！';
					} else if (now > 11 && now <= 14) {
						text = '中午了，工作了一个上午，现在是午餐时间！';
					} else if (now > 14 && now <= 17) {
						text = '午后很容易犯困呢，今天的运动目标完成了吗？';
					} else if (now > 17 && now <= 19) {
						text = '傍晚了！窗外夕阳的景色很美丽呢，最美不过夕阳红~~';
					} else if (now > 19 && now <= 21) {
						text = '晚上好，今天过得怎么样？';
					} else if (now > 21 && now <= 23) {
						text = '已经这么晚了呀，早点休息吧，晚安~~';
					} else {
						text = '嗨~ 快来逗我玩吧！';
					}
				} else {
					text = '欢迎阅读<span style="color:#0099cc;">「 ' + document.title.split(' - ')[0] + ' 」</span>';
				}
			}
			showMessage(text, 12000);
		})();

		liveTlakTimer = setInterval(function () {
			showHitokoto();
		}, 15000);

		function showHitokoto() {
			if (sessionStorage.getItem("Sleepy") !== "1") {
				if (!AITalkFlag) {
					$.getJSON('https://v1.hitokoto.cn/', function (result) {
						talkValTimer();
						showMessage(result.hitokoto, 0);
					});
				}
			} else {
				hideMessage(0);
				if (sleepTimer_ == null) {
					sleepTimer_ = setInterval(function () {
						checkSleep();
					}, 200);
				}
			}
		}

		function checkSleep() {
			var sleepStatu = sessionStorage.getItem("Sleepy");
			if (sleepStatu !== '1') {
				talkValTimer();
				showMessage('你回来啦~', 0);
				clearInterval(sleepTimer_);
				sleepTimer_ = null;
			}
		}

		function showMessage(text, timeout) {
			if (Array.isArray(text)) text = text[Math.floor(Math.random() * text.length + 1) - 1];
			$('.message').stop();
			$('.message').html(text);
			$('.message').fadeTo(200, 1);
			//if (timeout === null) timeout = 5000;
			//hideMessage(timeout);
		}
		function talkValTimer() {
			$('#live_talk').val('1');
		}

		function hideMessage(timeout) {
			//$('.message').stop().css('opacity',1);
			if (timeout === null) timeout = 5000;
			$('.message').delay(timeout).fadeTo(200, 0);
		}

		function initLive2d() {
			$('#hideButton').on('click', function () {
				if (AIFadeFlag) {
					return false;
				} else {
					AIFadeFlag = true;
					localStorage.setItem("live2dhidden", "0");
					$('#landlord').fadeOut(200);
					$('#open_live2d').delay(200).fadeIn(200);
					setTimeout(function () {
						AIFadeFlag = false;
					}, 300);
				}
			});
			$('#open_live2d').on('click', function () {
				if (AIFadeFlag) {
					return false;
				} else {
					AIFadeFlag = true;
					localStorage.setItem("live2dhidden", "1");
					$('#open_live2d').fadeOut(200);
					$('#landlord').delay(200).fadeIn(200);
					setTimeout(function () {
						AIFadeFlag = false;
					}, 300);
				}
			});
			$('#youduButton').on('click', function () {
				if ($('#youduButton').hasClass('doudong')) {
					var typeIs = $('#youduButton').attr('data-type');
					$('#youduButton').removeClass('doudong');
					$('body').removeClass(typeIs);
					$('#youduButton').attr('data-type', '');
				} else {
					var duType = $('#duType').val();
					var duArr = duType.split(",");
					var dataType = duArr[Math.floor(Math.random() * duArr.length)];

					$('#youduButton').addClass('doudong');
					$('#youduButton').attr('data-type', dataType);
					$('body').addClass(dataType);
				}
			});
			if (apiKey) {
				$('#showInfoBtn').on('click', function () {
					var live_statu = $('#live_statu_val').val();
					if (live_statu == "0") {
						return
					} else {
						$('#live_statu_val').val("0");
						$('.live_talk_input_body').fadeOut(500);
						AITalkFlag = false;
						showHitokoto();
						$('#showTalkBtn').show();
						$('#showInfoBtn').hide();
					}
				});
				$('#showTalkBtn').on('click', function () {
					var live_statu = $('#live_statu_val').val();
					if (live_statu == "1") {
						return
					} else {
						$('#live_statu_val').val("1");
						$('.live_talk_input_body').fadeIn(500);
						AITalkFlag = true;
						$('#showTalkBtn').hide();
						$('#showInfoBtn').show();

					}
				});
				$('#talk_send').on('click', function () {
					var info_ = $('#AIuserText').val();
					var userid_ = $('#AIuserName').val();
					if (info_ == "") {
						showMessage('写点什么吧！', 0);
						return;
					}
					if (userid_ == "") {
						showMessage('聊之前请告诉我你的名字吧！', 0);
						return;
					}
					showMessage('思考中~', 0);
					let protocol = window.location.protocol.indexOf("s") > 0 ? "https" : "http";
					$.ajax({
						type: "get",
						url: `${protocol}://www.tuling123.com/openapi/api?key=${apiKey}&info=${info_}`,
						dataType: "json",
						success: function (res) {
							talkValTimer();
							showMessage(res.text, 0);
							$('#AIuserText').val("");
							sessionStorage.setItem("live2duser", userid_);
						},
						error: function (e) {
							talkValTimer();
							showMessage('似乎有什么错误，请和站长联系！', 0);
						}
					});
				});
			} else {
				$('#showInfoBtn').hide();
				$('#showTalkBtn').hide();
			}
			//获取音乐信息初始化
			var bgmListInfo = $('input[name=live2dBGM]');
			if (bgmListInfo.length == 0) {
				$('#musicButton').hide();
			} else {
				var bgmPlayNow = parseInt($('#live2d_bgm').attr('data-bgm'));
				var bgmPlayTime = 0;
				var live2dBGM_Num = sessionStorage.getItem("live2dBGM_Num");
				var live2dBGM_PlayTime = sessionStorage.getItem("live2dBGM_PlayTime");
				if (live2dBGM_Num) {
					if (live2dBGM_Num <= $('input[name=live2dBGM]').length - 1) {
						bgmPlayNow = parseInt(live2dBGM_Num);
					}
				}
				if (live2dBGM_PlayTime) {
					bgmPlayTime = parseInt(live2dBGM_PlayTime);
				}
				var live2dBGMSrc = bgmListInfo.eq(bgmPlayNow).val();
				$('#live2d_bgm').attr('data-bgm', bgmPlayNow);
				$('#live2d_bgm').attr('src', live2dBGMSrc);
				$('#live2d_bgm')[0].currentTime = bgmPlayTime;
				$('#live2d_bgm')[0].volume = 0.5;
				var live2dBGM_IsPlay = sessionStorage.getItem("live2dBGM_IsPlay");
				var live2dBGM_WindowClose = sessionStorage.getItem("live2dBGM_WindowClose");
				if (live2dBGM_IsPlay == '0' && live2dBGM_WindowClose == '0') {
					$('#live2d_bgm')[0].play();
					$('#musicButton').addClass('play');
				}
				sessionStorage.setItem("live2dBGM_WindowClose", '1');
				$('#musicButton').on('click', function () {
					if ($('#musicButton').hasClass('play')) {
						$('#live2d_bgm')[0].pause();
						$('#musicButton').removeClass('play');
						sessionStorage.setItem("live2dBGM_IsPlay", '1');
					} else {
						$('#live2d_bgm')[0].play();
						$('#musicButton').addClass('play');
						sessionStorage.setItem("live2dBGM_IsPlay", '0');
					}
				});
				window.onbeforeunload = function () {
					sessionStorage.setItem("live2dBGM_WindowClose", '0');
					if ($('#musicButton').hasClass('play')) {
						sessionStorage.setItem("live2dBGM_IsPlay", '0');
					}
				}
				document.getElementById('live2d_bgm').addEventListener("timeupdate", function () {
					var live2dBgmPlayTimeNow = document.getElementById('live2d_bgm').currentTime;
					sessionStorage.setItem("live2dBGM_PlayTime", live2dBgmPlayTimeNow);
				});
				document.getElementById('live2d_bgm').addEventListener("ended", function () {
					var listNow = parseInt($('#live2d_bgm').attr('data-bgm'));
					listNow++;
					if (listNow > $('input[name=live2dBGM]').length - 1) {
						listNow = 0;
					}
					var listNewSrc = $('input[name=live2dBGM]').eq(listNow).val();
					sessionStorage.setItem("live2dBGM_Num", listNow);
					$('#live2d_bgm').attr('src', listNewSrc);
					$('#live2d_bgm')[0].play();
					$('#live2d_bgm').attr('data-bgm', listNow);
				});
				document.getElementById('live2d_bgm').addEventListener("error", function () {
					$('#live2d_bgm')[0].pause();
					$('#musicButton').removeClass('play');
					showMessage('音乐似乎加载不出来了呢！', 0);
				});
			}
			//获取用户名
			var live2dUser = sessionStorage.getItem("live2duser");
			if (live2dUser !== null) {
				$('#AIuserName').val(live2dUser);
			}
			//获取位置
			var landL = sessionStorage.getItem("historywidth");
			var landB = sessionStorage.getItem("historyheight");
			if (landL == null || landB == null) {
				landL = '5px'
				landB = '0px'
			}
			$('#landlord').css('left', landL + 'px');
			$('#landlord').css('bottom', landB + 'px');
			//移动
			function getEvent() {
				return window.event || arguments.callee.caller.arguments[0];
			}
			var smcc = document.getElementById("landlord");
			var moveX = 0;
			var moveY = 0;
			var moveBottom = 0;
			var moveLeft = 0;
			var moveable = false;
			var docMouseMoveEvent = document.onmousemove;
			var docMouseUpEvent = document.onmouseup;
			smcc.onmousedown = function () {
				var ent = getEvent();
				moveable = true;
				moveX = ent.clientX;
				moveY = ent.clientY;
				var obj = smcc;
				moveBottom = parseInt(obj.style.bottom);
				moveLeft = parseInt(obj.style.left);
				if (isFirefox = navigator.userAgent.indexOf("Firefox") > 0) {
					window.getSelection().removeAllRanges();
				}
				document.onmousemove = function () {
					if (moveable) {
						var ent = getEvent();
						var x = moveLeft + ent.clientX - moveX;
						var y = moveBottom + (moveY - ent.clientY);
						obj.style.left = x + "px";
						obj.style.bottom = y + "px";
					}
				};
				document.onmouseup = function () {
					if (moveable) {
						var historywidth = obj.style.left;
						var historyheight = obj.style.bottom;
						historywidth = historywidth.replace('px', '');
						historyheight = historyheight.replace('px', '');
						sessionStorage.setItem("historywidth", historywidth);
						sessionStorage.setItem("historyheight", historyheight);
						document.onmousemove = docMouseMoveEvent;
						document.onmouseup = docMouseUpEvent;
						moveable = false;
						moveX = 0;
						moveY = 0;
						moveBottom = 0;
						moveLeft = 0;
					}
				};
			};
		}
		$(document).ready(function () {
			var AIimgSrc = [];
			let chooseLive2d = 'plt'
			if (chooseLive2d === 'histoire') {
				AIimgSrc.push(message_Path + "model/histoire/histoire.1024/texture_00.png");
				AIimgSrc.push(message_Path + "model/histoire/histoire.1024/texture_01.png");
				AIimgSrc.push(message_Path + "model/histoire/histoire.1024/texture_02.png");
				AIimgSrc.push(message_Path + "model/histoire/histoire.1024/texture_03.png");
			} else if (chooseLive2d === 'rem') {
				AIimgSrc.push(message_Path + "model/rem/remu2048/texture_00.png");
			} else if (chooseLive2d === 'aoba') {
				AIimgSrc.push(message_Path + "model/aoba/textures/texture_00.png");
			} else if (chooseLive2d === 'hijiki') {
				AIimgSrc.push(message_Path + "model/hijiki/moc/hijiki.2048/texture_00.png");
			} else if (chooseLive2d === 'tororo') {
				AIimgSrc.push(message_Path + "model/tororo/moc/tororo.2048/texture_00.png");
			} else if (chooseLive2d === 'plt') {
				AIimgSrc.push(message_Path + "model/plt/moc/plt.2048/texture_00.png");
			}
			var images = [];
			var imgLength = AIimgSrc.length;
			var loadingNum = 0;
			for (var i = 0; i < imgLength; i++) {
				images[i] = new Image();
				images[i].src = AIimgSrc[i];
				images[i].onload = function () {
					loadingNum++;
					if (loadingNum === imgLength) {
						var live2dhidden = localStorage.getItem("live2dhidden");
						if (live2dhidden === "0") {
							setTimeout(function () {
								$('#open_live2d').fadeIn(200);
							}, 1300);
						} else {
							setTimeout(function () {
								$('#landlord').fadeIn(200);
							}, 1300);
						}
						let model = '';
						if (chooseLive2d === 'histoire') {
							model = message_Path + "model/histoire/model.json";
						} else if (chooseLive2d === 'rem') {
							model = message_Path + "model/rem/model.json";
						} else if (chooseLive2d === 'aoba') {
							model = message_Path + "model/aoba/model.json";
						} else if (chooseLive2d === 'hijiki') {
							model = message_Path + "model/hijiki/hijiki.model.json";
						} else if (chooseLive2d === 'tororo') {
							model = message_Path + "model/tororo/tororo.model.json";
						} else if (chooseLive2d === 'plt') {
							model = message_Path + "model/plt/model.json?v=1617466520";
						}
						setTimeout(function () {
							loadlive2d("live2d", model);
						}, 1000);
						initLive2d();
						images = null;
					}
				}
			}
		});
	}
</script>
  
  
</div>
<script>

  let sideBarOpen = 'sidebar-open';
  let body = document.body;
  let back2Top = document.querySelector('#back_to_top'),
    back2TopText = document.querySelector('#back_to_top_text'),
    drawerBox = document.querySelector('#drawer_box'),
    rightSideBar = document.querySelector('.sidebar'),
    viewport = document.querySelector('body');

  function scrollAnimation(currentY, targetY) {

    let needScrollTop = targetY - currentY
    let _currentY = currentY
    setTimeout(() => {
      const dist = Math.ceil(needScrollTop / 10)
      _currentY += dist
      window.scrollTo(_currentY, currentY)
      if (needScrollTop > 10 || needScrollTop < -10) {
        scrollAnimation(_currentY, targetY)
      } else {
        window.scrollTo(_currentY, targetY)
      }
    }, 1)
  }

  back2Top.addEventListener("click", function (e) {
    scrollAnimation(document.scrollingElement.scrollTop, 0);
    e.stopPropagation();
    return false;
  });

  window.addEventListener('scroll', function (e) {
    let percent = document.scrollingElement.scrollTop / (document.scrollingElement.scrollHeight - document.scrollingElement.clientHeight) * 100;
    if (percent > 1 && !back2Top.classList.contains('back-top-active')) {
      back2Top.classList.add('back-top-active');
    }
    if (percent == 0) {
      back2Top.classList.remove('back-top-active');
    }
    if (back2TopText) {
      back2TopText.textContent = Math.floor(percent);
    }
  });


  let hasCacu = false;
  window.onresize = function () {
    calcuHeight();
  }

  function calcuHeight() {
    // 动态调整站点概览高度
    if (!hasCacu && back2Top.classList.contains('pisces') || back2Top.classList.contains('gemini')) {
      let sideBar = document.querySelector('.sidebar');
      let navUl = document.querySelector('#site_nav');
      sideBar.style = 'margin-top:' + (navUl.offsetHeight + navUl.offsetTop + 15) + 'px;';
      hasCacu = true;
    }
  }
  calcuHeight();

  let open = false, MOTION_TIME = 300, RIGHT_MOVE_DIS = '320px';

  if (drawerBox) {
    let rightMotions = document.querySelectorAll('.right-motion');
    let right = drawerBox.classList.contains('right');

    let transitionDir = right ? "transition.slideRightIn" : "transition.slideLeftIn";

    let openProp, closeProp;
    if (right) {
      openProp = {
        paddingRight: RIGHT_MOVE_DIS
      };
      closeProp = {
        paddingRight: '0px'
      };
    } else {
      openProp = {
        paddingLeft: RIGHT_MOVE_DIS
      };
      closeProp = {
        paddingLeft: '0px'
      };
    }

    drawerBox.onclick = function () {
      open = !open;
      window.Velocity(rightSideBar, 'stop');
      window.Velocity(viewport, 'stop');
      window.Velocity(rightMotions, 'stop');
      if (open) {
        window.Velocity(rightSideBar, {
          width: RIGHT_MOVE_DIS
        }, {
          duration: MOTION_TIME,
          begin: function () {
            window.Velocity(rightMotions, transitionDir, {});
          }
        })
        window.Velocity(viewport, openProp, {
          duration: MOTION_TIME
        });
      } else {
        window.Velocity(rightSideBar, {
          width: '0px'
        }, {
          duration: MOTION_TIME,
          begin: function () {
            window.Velocity(rightMotions, {
              opacity: 0
            });
          }
        })
        window.Velocity(viewport, closeProp, {
          duration: MOTION_TIME
        });
      }
      for (let i = 0; i < drawerBox.children.length; i++) {
        drawerBox.children[i].classList.toggle('muse-line');
      }
      drawerBox.classList.toggle(sideBarOpen);
    }
  }

  // 链接跳转
  let newWindow = 'false'
  if (newWindow === 'true') {
    let links = document.querySelectorAll('.post-body a')
    links.forEach(item => {
      if (!item.classList.contains('btn')) {
        item.setAttribute("target", "_blank");
      }
    })
  }

  let faSearch = document.querySelector('#fa_search');
  faSearch && faSearch.addEventListener('click', function () {
    document.querySelector('#search_mask').style = ''
  })

  // 代码高亮
  hljs.initHighlightingOnLoad();
  
  // 离开当前页title变化
  var leaveTitle = "";
  if (leaveTitle) {
    document.addEventListener('visibilitychange', function () {
      if (document.visibilityState == 'hidden') {
        normal_title = document.title;
        document.title = leaveTitle;
      } else {
        document.title = normal_title;
      }
    });
  }

</script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
<script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script>

<script>
  let images = document.querySelectorAll('.section img');
  console.log(images);
  images.forEach(image => {
    if (image.classList.contains('no-fancybox')) {
      return;
    }

    var parent = image.parentElement;
    var next = image.nextElementSibling;
    parent.removeChild(image);
    var aelem = document.createElement('a');
    aelem.href = image.src;
    aelem.dataset['fancybox'] = 'images';
    aelem.dataset['rel'] = 'fancybox-button';
    aelem.classList.add('fancybox');
    aelem.appendChild(image);
    parent.insertBefore(aelem, next);
  })
</script>
    <div class="reward-mask" style="display: none;">
  <div class="reward-relative">
    <span class="close" aria-hidden="true">x</span>
    <div class="reward-body">
      <h2>感谢您的支持，我会继续努力的!</h2>
      <div class="reward-img-box">
        <div style="position: relative; width: 140px; height: 140px;">
          
          
          
        </div>
      </div>
      <p class="reward-word">扫码打赏，你说多少就多少</p>
      <p class="reward-tip">打开微信扫一扫，即可进行扫码打赏哦</p>
    </div>
    <div class="bottom">
      
      
    </div>
  </div>
</div>
<style>
  .reward-mask {
    position: fixed;
    z-index: 99999;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #00000054;
  }

  .reward-relative {
    position: relative;
    width: 480px;
    text-align: center;
    margin: 0 auto;
    border-radius: 5px;
    background-color: #fff;
    top: 50%;
    margin-top: -205px;
  }

  .reward-relative .close {
    position: absolute;
    right: 10px;
    font-weight: normal;
    font-size: 16px;
    color: #929292;
  }

  .reward-body {
    padding: 40px 20px 20px;
  }

  .bottom {
    display: flex;
  }

  .reward-btn {
    text-align: center;
  }

  .reward-btn-text {
    display: inline-block;
    cursor: pointer;
    width: 60px;
    height: 60px;
    line-height: 60px;
    border-radius: 50%;
    background-color: #ff9734;
    color: #FFF;
    margin-top: 20px;
  }

  .pay-text {
    margin-top: 10px;
    padding: 10px;
    flex: 1;
    transition: all .2s linear;
  }

  .pay-text:hover {
    background-color: #a5a5a536;
  }

  .reward-body h2 {
    padding-top: 10px;
    text-align: center;
    color: #a3a3a3;
    font-size: 16px;
    font-weight: normal;
    margin: 0 0 20px;
  }

  .reward-body h2:after,
  .reward-body h2:before {
    font-family: Arial, Helvetica, sans-serif;
    background: 0 0;
    width: 0;
    height: 0;
    font-style: normal;
    color: #eee;
    font-size: 80px;
    position: absolute;
    top: 20px;
  }

  .reward-body h2:before {
    content: '\201c';
    left: 50px;
  }

  .reward-body h2:after {
    content: '\201d';
    right: 80px;
  }

  .reward-img-box {
    display: inline-block;
    padding: 10px;
    border: 6px solid #ea5f00;
    margin: 0 auto;
    border-radius: 3px;
    position: relative;
  }

  .reward-img {
    position: absolute;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
  }

  @media (max-width: 767px) {
    .reward-relative {
      height: 100%;
      top: 0px;
      margin-top: 0;
      width: auto;
    }

    .reward-relative .bottom {
      flex-direction: column;
    }

    .reward-relative .pay-text {
      width: 80%;
      margin: 5px auto;
      border: 1px solid silver;
      padding: 6px;
      border-radius: 4px;
    }

    .reward-body h2:after {
      right: 40px;
    }

    .reward-body h2:after,
    .reward-body h2:before {
      font-size: 60px;
    }

    .reward-body h2:before {
      left: 20px;
    }
  }
</style>
<script>
  !function () {
    var mask = document.querySelector('.reward-mask');
    let close = document.querySelector('.reward-relative .close');
    let rewardBtn = document.querySelector('.reward-btn');

    let zfb = document.querySelector('#zfb'),
      wx = document.querySelector('#wx'),
      zfbBtn = document.querySelector('#zfbBtn'),
      wxBtn = document.querySelector('#wxBtn');

    if (zfbBtn && wxBtn) {
      zfbBtn.addEventListener('click', () => {
        window.Velocity(zfb, 'transition.slideLeftIn', {
          duration: 400
        });
        window.Velocity(wx, 'transition.slideRightOut', {
          display: 'none',
          duration: 400
        });
      });

      wxBtn.addEventListener('click', () => {
        window.Velocity(wx, 'transition.slideRightIn', {
          duration: 400
        });
        window.Velocity(zfb, 'transition.slideLeftOut', {
          display: 'none',
          duration: 400
        });
      });
    }

    rewardBtn && rewardBtn.addEventListener('click', (e) => {
      window.Velocity(mask, 'transition.slideDownIn', {
        duration: 400
      })
    });

    close.addEventListener('click', (e) => {
      e.preventDefault();
      window.Velocity(mask, 'transition.slideUpOut', {
        duration: 400
      })
    })
  }()
</script>

  </div>
</body>

<input hidden id="copy" />
<script>
  !function () {
    let times = document.querySelectorAll('.publish-time');
    for (let i = 0; i < times.length; i++) {
      let date = times[i].dataset.t;
      let time = Math.floor((new Date().getTime() - new Date(date).getTime()) / 1000);
      if (time < 60) {
        str = time + '秒之前';
      } else if (time < 3600) {
        str = Math.floor(time / 60) + '分钟之前';
      } else if (time >= 3600 && time < 86400) {
        str = Math.floor(time / 3600) + '小时之前';
      } else if (time >= 86400 && time < 259200) {
        str = Math.floor(time / 86400) + '天之前';
      } else {
        str = times[i].textContent;
      }
      times[i].textContent = str;
    }
  }();
</script>

<script>
  let language = '';
  if (language !== '') {
    let map = new Map();
    if (language === 'en') {
      map.set('search', 'Search');
      map.set('category', 'Categories');
      map.set('article', 'Articles');
      map.set('tag', 'Tags');
      map.set('top', 'Top');
      map.set('publish', 'published');
      map.set('minute', ' minutes');
      map.set('read-more', 'Read More');
      map.set('view', 'View');
      map.set('words', ' words');
      map.set('category-in', 'category in');
      map.set('preview', 'Meta');
      map.set('index', 'Toc');
      map.set('no-archives', "You haven't created yet");
      map.set('archives', " articles in total");
      map.set('cloud-tags', " tags in total");
      map.set('copyright', "Copyright: ");
      map.set('author', "Author: ");
      map.set('link', "Link: ");
      map.set('leave-message', "Leave a message");
      map.set('format', "Links Format");
      map.set('site-name', "Name: ");
      map.set('site-link', "Link: ");
      map.set('site-desc', "Desc: ");
      map.set('stat', " related results, taking ");
      map.set('stat-time', " ms");
      map.set('site-img', "Image: ");
    }

    if (map.size > 0) {
      let lanElems = document.querySelectorAll('.language');
      lanElems.forEach(elem => {
        let lan = elem.dataset.lan, text = map.get(lan);
        if (elem.__proto__ === HTMLInputElement.prototype) {
          elem.placeholder = text
        } else {
          if (elem.dataset.count) {
            text = elem.dataset.count + text;
          }
          elem.textContent = text;
        }
      })
    }
  }
  //拿来主义(真香)^_^，Clipboard 实现摘自掘金 https://juejin.im/post/5aefeb6e6fb9a07aa43c20af
  window.Clipboard = (function (window, document, navigator) {
    var textArea,
      copy;

    // 判断是不是ios端
    function isOS() {
      return navigator.userAgent.match(/ipad|iphone/i);
    }
    //创建文本元素
    function createTextArea(text) {
      textArea = document.createElement('textArea');
      textArea.value = text;
      textArea.style.width = 0;
      textArea.style.height = 0;
      textArea.clientHeight = 0;
      textArea.clientWidth = 0;
      document.body.appendChild(textArea);
    }
    //选择内容
    function selectText() {
      var range,
        selection;

      if (isOS()) {
        range = document.createRange();
        range.selectNodeContents(textArea);
        selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
        textArea.setSelectionRange(0, 999999);
      } else {
        textArea.select();
      }
    }

    //复制到剪贴板
    function copyToClipboard() {
      try {
        document.execCommand("Copy")
      } catch (err) {
        alert("复制错误！请手动复制！")
      }
      document.body.removeChild(textArea);
    }

    copy = function (text) {
      createTextArea(text);
      selectText();
      copyToClipboard();
    };

    return {
      copy: copy
    };
  })(window, document, navigator);

  function copyCode(e) {
    if (e.srcElement.tagName === 'SPAN' && e.srcElement.classList.contains('copy-code')) {
      let code = e.currentTarget.querySelector('code');
      var text = code.innerText;
      if (e.srcElement.textContent === '复制成功') {
        return;
      }
      e.srcElement.textContent = '复制成功';
      (function (elem) {
        setTimeout(() => {
          if (elem.textContent === '复制成功') {
            elem.textContent = '复制代码'
          }
        }, 1000);
      })(e.srcElement)
      Clipboard.copy(text);
    }
  }

  let pres = document.querySelectorAll('pre');
  pres.forEach(pre => {
    let code = pre.querySelector('code');
    let copyElem = document.createElement('span');
    copyElem.classList.add('copy-code');
    copyElem.textContent = '复制代码';
    pre.appendChild(copyElem);
    pre.onclick = copyCode
  })

</script>
<script src="/media/js/motion.js"></script>


<script src="https://cdn.jsdelivr.net/gh/cferdinandi/smooth-scroll/dist/smooth-scroll.polyfills.min.js"></script>
<script>
  var scroll = new SmoothScroll('a[href*="#"]', {
    speed: 200
  });
</script>



<script src="/media/js/cool.js"></script>



</html>